package com.zed.code.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zed.code.base.TResponse;
import com.zed.code.enums.Constant;
import com.zed.code.request.PushReqInfo;
import com.zed.code.request.QueryStartChargeReqForFD;
import com.zed.code.request.QueryStopChargeReqForFD;
import com.zed.code.response.QueryStartChargeResForFD;
import com.zed.code.response.QueryStopChargeResForFD;
import com.zed.code.service.PushService;
import com.zed.code.util.AESUtil;
import com.zed.code.util.GDEVHttpClient;
import com.zed.code.util.PubFetchTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service("pushService")
public class PushServiceImpl implements PushService {

    private static Logger log = LoggerFactory.getLogger(PushServiceImpl.class);

    private static ExecutorService threadPool = Executors.newFixedThreadPool(20);

    private static final String OPERATOR_ID = "314838869";

    @Autowired
    private RedisHandle redisHandle;

    public void pushToPlatform(List<PushReqInfo> push) {
        for (PushReqInfo pushReqInfo:push){
            threadPool.execute(new pushTask(redisHandle,pushReqInfo.getMethod(), pushReqInfo.getData(), pushReqInfo.getURL(),pushReqInfo.getOperatorSecret(),pushReqInfo.getAesKey(),pushReqInfo.getAesIv(),pushReqInfo.getSignKey()));
        }
        //setup 2

    }

    private static class pushTask implements Runnable {
        private RedisHandle redisHandle;
        private String method;
        private String data;
        private String URL;
        private String OperatorSecret;
        private String aesKey;
        private String aesIv;
        private String signKey;

        public pushTask(RedisHandle redisHandle,String method, String data, String URL,String OperatorSecret,String aesKey,String aesIv,String signKey) {
            this.URL = URL;
            this.method = method;
            this.data = data;
            this.OperatorSecret=OperatorSecret;
            this.aesKey=aesKey;
            this.aesIv=aesIv;
            this.signKey=signKey;
            this.redisHandle=redisHandle;
        }

        private String push_query_token(String resultJson) {
            JSONObject res ;
            try {
                JSONObject jsonObject = PubFetchTool.dealParam(resultJson, aesKey,aesIv,signKey);
                HashMap<String, Object> headers = new HashMap<String, Object>();
                headers.put("Content-Type", "application/json;charset=UTF-8");
                //请求query_token的方法,查询token
                String result = "";
                log.info("请求查询token url={},data={}",URL + "query_token",jsonObject.toJSONString());
                result= GDEVHttpClient.doPostForGDEV(URL + "query_token",jsonObject.toJSONString());
                res=JSONObject.parseObject(result);
                log.info("token 返回内容res={}",JSON.toJSONString(res));
                res = JSONObject.parseObject(AESUtil.Decrypt(res.getString(Constant.Data),aesKey,
                        aesIv));// 对返回结果解密
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            log.info("解密后的data={}",res);
            String AccessToken=res.getString("AccessToken");
            Long TokenAvailableTime=res.getLong("TokenAvailableTime");
            redisHandle.set(OperatorSecret,AccessToken,TokenAvailableTime);
            return AccessToken;
        }

        @Override
        public void run() {
            log.info("启动线程请求数据data={}",JSON.toJSONString(data));
            if (data != null) {
                try {
                    //setup 1 查询redis的token
                    Object tokenObject=redisHandle.get(OperatorSecret);
                    String token;
                    if (tokenObject!=null&&!tokenObject.equals("")){//查到token
                        log.info("通过redis查到token={}",tokenObject);
                        token= String.valueOf(tokenObject);
                    }else {//未查到token，去请求
                        log.info("通过redis未查到token");
                        Map req = new HashMap();
                        req.put(Constant.OperatorSecret,OperatorSecret);
                        req.put(Constant.OperatorID,OPERATOR_ID);
                        token=push_query_token(JSON.toJSONString(req));
                        if (token==null||"".equals(token)){
                            return;
                        }
                    }
                    log.info("请求入参 url={} data={} token={}",URL+method,data,token);
                    String res=GDEVHttpClient.doPostForGDEV(URL+method,data,token);
                    JSONObject jsonObject =JSONObject.parseObject(res);
                    log.info("请求返回 res={}",res);
                    String ret = jsonObject.getString("Ret");
                    jsonObject = JSONObject.parseObject(AESUtil.Decrypt(jsonObject.getString(Constant.Data),aesKey,
                            aesIv));// 对返回结果解密
                    log.info("请求返回Data解密数据 jsonObject={}",jsonObject);
                    if (ret==null||!"0".equals(ret)){//错误重新请求
                        Map req = new HashMap();
                        req.put(Constant.OperatorSecret,OperatorSecret);
                        req.put(Constant.OperatorID,OPERATOR_ID);
                        token=push_query_token(JSON.toJSONString(req));
                        if (token==null||"".equals(token)){
                            return;
                        }
                        GDEVHttpClient.doPostForGDEV(URL+method,data,token);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info(e.getMessage());
                }
            }
        }
    }}
